# -*- coding: utf-8 -*-
# @Author : breeze
# @Date   : 2019/10/22
# @File   : R16_PercentageOfOverdueBusinessCheck_WHB.py
# @E-mail : wangbaoshan@bbdservice.com

'''eof
name:我行逾期业务占比
code:R16_PercentageOfOverdueBusinessCheck_WHB
tableName:
columnName:
groups:弱规则>个人及企业征信校验
dependencies:EC_DSJ,IC_DSJ
type:常用指标
datasourceType:在线指标
description:
eof'''

import sys
import re
import datetime
import json

reload(sys)
sys.setdefaultencoding('utf-8')

null_type_list = ['', ' ', None, 'null', 'Null', 'NULL', '/', '-', '--']


def getTable(table_Name):
    try:
        data = EC_DSJ['data'].get(table_Name)
        if data in null_type_list:
            return None
        else:
            # 存在1条为空的数据[{}]
            if isinstance(data, list) and len(data) == 1 and data[0]['ReportNo'] in null_type_list:
                return [{}]
            # 存在空list []
            elif isinstance(data, list) and len(data) == 0:
                return None
            else:
                return data
    except:
        return None


def getICTable(table_Name):
    try:
        data = IC_DSJ['data'].get(table_Name)
        if data in null_type_list:
            return None
        else:
            # 存在1条为空的数据[{}]
            if isinstance(data, list) and len(data) == 1 and data[0]['reportNo'] in null_type_list:
                return [{}]
            # 存在空list []
            elif isinstance(data, list) and len(data) == 0:
                return None
            else:
                return data
    except:
        return None


def int_check(target):
    try:
        int(target)
        return True
    except:
        return False


def float_check(target):
    try:
        float(target)
        return True
    except:
        return False


# 返回前者是总数，后者是包含重庆银行的
def getValue(base, column1, column2):
    if base == [{}]:
        return (0, 0)
    elif base in null_type_list or not isinstance(base, list):
        return None
    else:
        result1 = 0
        result2 = 0
        flag = False
        for i in base:
            try:
                value1 = i.get(column1)
                value2 = i.get(column2)
                if value1 not in null_type_list and float_check(value2):
                    flag = True
                    result1 += float(value2)
                    if u"重庆银行" in value1:
                        result2 += float(value2)
            except:
                continue
        return (result1, result2) if flag else None


# 返回前者是总数，后者是包含重庆银行的
def getFactor10(base):
    if base == [{}]:
        return (0, 0)
    elif base in null_type_list or not isinstance(base, list):
        return None
    else:
        result1 = 0
        result2 = 0
        flag = False
        for i in base:
            try:
                latest24State = i.get("latest24State")
                financeOrg = i.get("financeOrg")
                usedCreditLimitAmount = i.get("usedCreditLimitAmount")
                if financeOrg not in null_type_list and float_check(usedCreditLimitAmount) \
                        and latest24State not in null_type_list and len(latest24State) == 24:
                    flag = True
                    value = 0
                    if int_check(latest24State[23]) and int(latest24State[23]) >= 3:
                        value = float(usedCreditLimitAmount)
                    result1 += value
                    if u"重庆银行" in financeOrg:
                        result2 += value
            except:
                continue
        return (result1, result2) if flag else None


def getRule16():
    ECRUnpaidDebtInterest = getTable('ECRUnpaidDebtInterest')
    ECRUnpaidBadLoanInfo = getTable('ECRUnpaidBadLoanInfo')
    ECRUnpaidBadTradeFinancing = getTable('ECRUnpaidBadTradeFinancing')
    ECRUnpaidBadFactoring = getTable('ECRUnpaidBadFactoring')
    ECRUnpaidBadBankAcceptance = getTable('ECRUnpaidBadBankAcceptance')
    ECRUnpaidBadLetterCredit = getTable('ECRUnpaidBadLetterCredit')
    ECRUnpaidBadLetterGuarantee = getTable('ECRUnpaidBadLetterGuarantee')
    ICRLoanInfo002 = getICTable('ICRLoanInfo002*Loan')
    ICRLoancardInfo002 = getICTable('ICRLoancardInfo002*Card')
    ICRStdLoancardInfo002 = getICTable('ICRStdLoancardInfo002*Std')

    resultList = []

    factor1 = getValue(ECRUnpaidDebtInterest, 'Financecode', 'Owebalancetormb')
    resultList.append(factor1)
    factor2 = getValue(ECRUnpaidBadLoanInfo, 'Financecode', 'Duebillbalance')
    resultList.append(factor2)
    factor3 = getValue(ECRUnpaidBadTradeFinancing, 'Financecode', 'Financingbalance')
    resultList.append(factor3)
    factor4 = getValue(ECRUnpaidBadFactoring, 'Financecode', 'Extendbalance')
    resultList.append(factor4)
    factor5 = getValue(ECRUnpaidBadBankAcceptance, 'Financecode', 'Posum')
    resultList.append(factor5)
    factor6 = getValue(ECRUnpaidBadLetterCredit, 'Financecode', 'AvailableBalance')
    resultList.append(factor6)
    factor7 = getValue(ECRUnpaidBadLetterGuarantee, 'Financecode', 'Letterbalance')
    resultList.append(factor7)
    factor8 = getValue(ICRLoanInfo002, 'financeOrg', 'currOverdueAmount')
    resultList.append(factor8)
    factor9 = getValue(ICRLoancardInfo002, 'financeOrg', 'currOverdueAmount')
    resultList.append(factor9)
    factor10 = getFactor10(ICRStdLoancardInfo002)
    resultList.append(factor10)

    resultList = [x for x in resultList if x != None]
    if len(resultList) > 0:
        denominator = 0
        numerator = 0
        for i in resultList:
            denominator += i[0]
            numerator += i[1]

        if denominator == 0 or numerator == 0:
            return 9999

        try:
            return numerator / denominator
        except:
            return 0

    else:
        return u"缺失值"


if __name__ == "__main__":
    file_obj = open(r'../data/WHB/R16_PercentageOfOverdueBusinessCheck_WHB/EC_DSJ.json', 'r')
    aa = file_obj.read()
    EC_DSJ = json.loads(aa, strict=False)
    file_obj = open(r'../data/WHB/R16_PercentageOfOverdueBusinessCheck_WHB/IC_DSJ.json', 'r')
    bb = file_obj.read()
    IC_DSJ = json.loads(bb, strict=False)
    aa = getRule16()
    print aa
result = getRule16()
